#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/7/19 22:43
# @Author  : hyang
# @File    : shelve_util.py
# @Software: python_utils

import shelve


class ShelveUtil(object):
    """
    使用Shelve存储提取对象
    """

    def __init__(self, file):
        self.file_obj = shelve.open(file)

    def save(self, key, value):
        """
         存储对象
        :param key:
        :param value:
        :return:
        """
        self.file_obj[key] = value

    def load(self, key):
        """
         获得对象
        :param key:
        :return:
        """
        return self.file_obj[key]

    def load_keys(self):
        """
        返回所有key
        :return:
        """
        return list(self.file_obj.keys())

    def del_obj(self, key):
        """
        删除object
        :return:
        """
        del self.file_obj[key]

    def __del__(self):
        self.file_obj.close()


if __name__ == '__main__':

    a = {'a': 1, 'b': 2}
    s = ShelveUtil('a.db')
    s.save('a', a)
    print(s.load('a'))
